import React, { Component } from 'react';
import {
  Text,
  View,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  Animated,
} from 'react-native';
import { px2dp } from 'bee/utils/px2dp';
import { sizes, colors } from 'bee/themes';
import Radio from 'bee/components/Radio';
import { PrimaryBtn } from 'bee/components/Buttons';
import { RadioPicker } from 'bee/components/MakePlan';
import { CuttingLine } from 'bee/components/Line';
import { Icons, Names } from 'bee/components/Icon/Icons';
import { Icon } from 'bee/components/Icon';
import { Attache } from 'bee/components/Attache';
// @flow
type Props = {
  money: string,
  navigation: object,
};

// Renewal:续期
const Renewal = 'Renewal';
// CashValue:现金价值自动垫交保费
const CashValue = 'CashValue';

export default class TransferPrice extends Component<Props> {
  static defaultProps = {
    // serviceSecialist: 'zhouzhou', // 服务专员
    money: '5678',
  };

  constructor() {
    super();

    this.abstractRotateFunction = this.abstractRotateFunction.bind(this);
    this.rotate = this.rotate.bind(this);
    this.renderCashValue = this.renderCashValue.bind(this);
    this.renderRenewalAddCard = this.renderRenewalAddCard.bind(this);
    this.renderRenewalPayment = this.renderRenewalPayment.bind(this);
    this.detailBotton = this.detailBotton.bind(this);

    this.state = {
      // firstPeriodCardFlag: 是否已添加首期银行卡标识 true：已添加 false：未添加
      firstPeriodCardFlag: false,
      // 续期银行卡数组
      renewalCards: [],
      // 选中的续期银行卡
      selectedRenewalCard: null,
      // RenewalFlag:是否需要录入续期缴费 true：需要 false：不需要
      RenewalFlag: true,
      // RenewalMoreFlag: 续期缴费右侧小箭头 true：展开 false：收起
      RenewalMoreFlag: false,
      // rotation: 更多小图标 旋转初值
      RenewalRotation: new Animated.Value(0),
      // 现金价值自动垫交保费开关  true：展开 false：收起
      CashValueFlag: false,
      // 现金价值自动垫脚保费右侧旋转小箭头初始化
      CashValueRotation: new Animated.Value(0),
      // 首期银行卡详情
      CardDetail: null,
      // 同意授权 true：同意 false：不同意
      agreeAuthorization: false,
    };
  }

  // 右侧小箭头动画效果控制
  abstractRotateFunction(from, to, category) {
    if (category === Renewal) {
      this.state.RenewalRotation.setValue(from);
      Animated.timing(this.state.RenewalRotation, {
        toValue: to,
        duration: 500,
      }).start();
      this.setState({
        RenewalMoreFlag: !this.state.RenewalMoreFlag,
      });
    } else {
      this.state.CashValueRotation.setValue(from);
      Animated.timing(this.state.CashValueRotation, {
        toValue: to,
        duration: 500,
      }).start();
      this.setState({
        CashValueFlag: !this.state.CashValueFlag,
      });
    }
  }

  // 控制两个小箭头的旋转方向 传递的不是引用 是值
  rotate(category) {
    let flag;
    switch (category) {
      case Renewal:
        flag = this.state.RenewalMoreFlag;
        break;
      case CashValue:
        flag = this.state.CashValueFlag;
        break;
      default:
        // never used 废弃值
        flag = 4;
    }
    if (flag) {
      // true 箭头向下转 打开页面
      this.abstractRotateFunction(1, 0, category);
    } else {
      // false 箭头向右转 合起页面
      this.abstractRotateFunction(0, 1, category);
    }
  }

  // 右侧小箭头
  detailBotton(category) {
    let rotation;
    switch (category) {
      case Renewal:
        rotation = this.state.RenewalRotation;
        break;
      case CashValue:
        rotation = this.state.CashValueRotation;
        break;
      default:
        rotation = 4;
    }
    return (
      <Animated.Text
        style={[
          styles.iconfont,
          styles.iconfontMore,
          {
            // backgroundColor: 'blue',
            transform: [
              {
                rotate: rotation.interpolate({
                  inputRange: [0, 1],
                  outputRange: ['0deg', '90deg'],
                }),
              },
            ],
          },
        ]}
        onPress={() => this.rotate(category)}
      >
        {Icons[Names.gengduofuben]}
      </Animated.Text>
    );
  }

  // 显示“现金价值垫交保费”条款须知
  cashValueDetail() {
    return this.state.CashValueFlag ? (
      <View>
        <CuttingLine />
        <Text style={styles.cashValueDetailBox}>
          如分期交付的保险费超过宽限期限仍未交付，本公司将以本保险合同的现金价值自动垫交应付的保险费。。。。
        </Text>
      </View>
    ) : null;
  }

  // 添加银行卡组件
  renderAddCard() {
    // 判断首期银行卡是否添加了
    // 打桩
    console.log('firstPeriodCardFlag:', this.state.firstPeriodCardFlag);
    console.log('CardDetail:', this.state.CardDetail);
    console.log('renewalCards:', this.state.renewalCards);
    return this.state.firstPeriodCardFlag ? (
      // 已添加首期银行卡
      <View>
        <CuttingLine />
        <View style={styles.firstPeriodCardBox}>
          <View style={styles.firstPeriodCardDetailText}>
            {/* 银行名 */}
            <Text style={[styles.littleTextStyle, styles.bankDetailText]}>
              {this.state.CardDetail.bank}
            </Text>
            {/* 银行卡号 */}
            <Text style={[styles.littleTextStyle, styles.bankDetailText]}>
              {this.state.CardDetail.cardNumber}
            </Text>
            {/* 转账限额 */}
            <Text style={[styles.cashValueDetailBox, styles.bankDetailText]}>
              {this.state.CardDetail.transferLimit}
            </Text>
          </View>
          <TouchableOpacity
            style={styles.changeBankCardBox}
            onPress={() =>
              this.props.navigation.navigate('BankCardRecording', {
                callback: ({
                  username,
                  bank,
                  province,
                  cardNumber,
                  transferLimit,
                }) => {
                  let renewalCardsArray = this.state.renewalCards;
                  renewalCardsArray = renewalCardsArray.filter(
                    (item, index) => index !== 0
                  );
                  const detail = {
                    username,
                    bank,
                    province,
                    cardNumber,
                    transferLimit,
                  };
                  this.setState({
                    firstPeriodCardFlag: true,
                    CardDetail: detail,
                    renewalCards: [detail, ...renewalCardsArray],
                  });
                  console.log('renewalCardsArray:', renewalCardsArray);
                },
              })
            }
          >
            <Text style={styles.changeBankCard}>更换银行卡</Text>
            <Icon name={Names.gengduofuben} size={sizes.f1} />
          </TouchableOpacity>
        </View>
      </View>
    ) : (
      // 未添加首期银行卡
      <View>
        <CuttingLine />
        <TouchableOpacity
          style={styles.addCardBox}
          onPress={() =>
            this.props.navigation.navigate('BankCardRecording', {
              callback: ({
                username,
                bank,
                province,
                cardNumber,
                transferLimit,
              }) => {
                this.setState({
                  firstPeriodCardFlag: true,
                  CardDetail: {
                    username,
                    bank,
                    province,
                    cardNumber,
                    transferLimit,
                  },
                  renewalCards: [
                    {
                      username,
                      bank,
                      province,
                      cardNumber,
                      transferLimit,
                    },
                    ...this.state.renewalCards,
                  ],
                });
              },
            })
          }
          // 点击添加银行卡
        >
          <Text style={styles.middleTextStyle}>
            <Icon name={Names.yinhangqia} size={sizes.f4} />
            <Text style={styles.addCardText}>添加银行卡付款</Text>
          </Text>
          <Icon name={Names.gengduofuben} size={sizes.f3} />
        </TouchableOpacity>
      </View>
    );
  }

  // 渲染“续期交费”部分的展开信息
  renderRenewalAddCard() {
    // 如果打开了续期交费框，显示其内部结构
    return this.state.RenewalMoreFlag ? (
      <View style={{ marginLeft: px2dp(41 - 17) }}>
        {this.state.renewalCards.map((value, index) => {
          let str = value.cardNumber.toString();
          if (index === 0 && !str.endsWith('(同首期)')) {
            str += '(同首期)';
          }
          return (
            <View key={index} style={{ marginBottom: px2dp(10) }}>
              <RadioPicker
                key={index}
                index={index}
                value={str}
                isSelected={this.state.selectedRenewalCard === value}
                onPress={() => {
                  this.setState({
                    selectedRenewalCard: value,
                  });
                }}
              />
            </View>
          );
        })}
        <CuttingLine />
        <TouchableOpacity
          style={styles.addCardBox}
          onPress={() =>
            this.props.navigation.navigate('BankCardRecording', {
              callback: ({
                username,
                bank,
                province,
                cardNumber,
                transferLimit,
              }) => {
                this.setState({
                  renewalCards: [
                    ...this.state.renewalCards,
                    {
                      username,
                      bank,
                      province,
                      cardNumber,
                      transferLimit,
                    },
                  ],
                  selectedRenewalCard: this.state.renewalCards[
                    this.state.renewalCards.length - 1
                  ],
                });
              },
            })
          }
          // 点击添加银行卡
        >
          <Text style={styles.middleTextStyle}>
            <Icon name={Names.yinhangqia} size={sizes.f3} />
            <Text style={styles.addCardText}>添加银行卡付款</Text>
          </Text>
          <Icon name={Names.gengduofuben} size={sizes.f3} />
        </TouchableOpacity>
      </View>
    ) : null;
  }

  // 渲染“续期交费”
  renderRenewalPayment() {
    return this.state.RenewalFlag ? (
      <View>
        {/* 续期缴费 */}
        <View style={[styles.generalBox, styles.blank]}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginRight: px2dp(41 - 17),
            }}
          >
            <Text style={styles.titleTextStyle}>续期交费</Text>
            {this.detailBotton(Renewal)}
          </View>
          {this.renderRenewalAddCard()}
        </View>
      </View>
    ) : null;
  }

  // 渲染“现金价值自动垫交保费”
  renderCashValue() {
    return (
      <View>
        <View style={[styles.generalBox, styles.blank]}>
          <View style={styles.cashValueBox}>
            <View style={styles.radioView}>
              <Radio
                onPress={() => {
                  // console.log('item:', item);
                  // item.selected = !item.selected;
                  this.setState({
                    CashValueFlag: !this.state.CashValueFlag,
                  });
                  this.rotate(CashValue);
                }}
                selected={this.state.CashValueFlag}
              />
              <Text style={[styles.middleTextStyle, { lineHeight: px2dp(88) }]}>
                现金价值自动垫交保费
              </Text>
            </View>
            <View style={styles.cashValueRightText}>
              <Text
                style={[
                  styles.littleTextStyle,
                  { lineHeight: px2dp(88), marginRight: px2dp(16) },
                ]}
              >
                详情
              </Text>
              {this.detailBotton(CashValue)}
            </View>
          </View>
          {this.cashValueDetail()}
        </View>
      </View>
    );
  }

  // 渲染“授权条款”
  renderAuthorization = () => (
    <View>
      {/* 转账授权及其他说明 */}
      <View style={[styles.generalBox, styles.blank]}>
        <Text style={styles.titleTextStyle}>转账授权及其他说明</Text>
        {/* 分割线 */}
        <CuttingLine />
        <View style={styles.radioView}>
          <Radio
            onPress={() => {
              this.setState({
                agreeAuthorization: true,
              });
            }}
            selected={this.state.agreeAuthorization}
          />
          <Text style={[styles.middleTextStyle, { lineHeight: px2dp(88) }]}>
            我同意《转账及授权说明》
          </Text>
        </View>
        <Text style={styles.clause}>
          1、您是否已经拥有或正在申请其他保险公司的人身保险合同？{'\n'}
          {'\n'}
          2、您是否已经拥有或正在申请其他保险公司的人身保险合同？{'\n'}
          {'\n'}
          3、您是否已经拥有或正在申请其他保险公司的人身保险合同？{'\n'}
        </Text>
      </View>
    </View>
  );

  render() {
    return (
      <View style={{ flex: 1 }}>
        <ScrollView showsVerticalScrollIndicator style={styles.contentOuterBox}>
          {/* 服务专员 */}
          <Attache />
          {/* 头部转账收费信息 */}
          <View style={styles.generalBox}>
            <Text style={styles.titleTextStyle}>转账收费信息</Text>
            {/* 分割线 */}
            <CuttingLine />
            <View style={styles.moneyBox}>
              <Text style={styles.moneyUpper}>
                <Text style={styles.figure}>{this.props.money}</Text>
                <Text style={styles.littleTextStyle}> 元</Text>
              </Text>
              <Text style={styles.littleTextStyle}>合计保费</Text>
            </View>
            {this.renderAddCard()}
          </View>
          {this.renderRenewalPayment()}
          {this.renderCashValue()}
          {this.renderAuthorization()}
        </ScrollView>
        <View style={styles.buttonStyle}>
          <PrimaryBtn
            text="上一步"
            onPress={() => {
              this.props.navigation.goBack();
            }}
            bgc={colors.white}
            fontColor={colors['1101']}
          />
          <PrimaryBtn
            text="下一步"
            onPress={() => {
              this.props.navigation.navigate('PaySuccess', {
                CardDetail: this.state.CardDetail,
                serviceSecialist: this.props.serviceSecialist,
                totalPrem: this.props.money,
              });
            }}
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  serviceSecialist: {
    lineHeight: px2dp(61),
    textAlign: 'center',
    fontSize: px2dp(22),
    color: colors['1103'],
  },
  contentOuterBox: {
    paddingHorizontal: px2dp(30),
    marginBottom: px2dp(130),
    // paddingBottom: px2dp(130),
  },
  generalBox: {
    borderRadius: px2dp(20),
    backgroundColor: colors.white,
    paddingHorizontal: px2dp(17),
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: colors['1104'],
  },
  titleTextStyle: {
    fontSize: sizes.f3,
    color: colors['1101'],
    lineHeight: px2dp(80),
    marginHorizontal: px2dp(41 - 17),
  },
  // cuttingLine: {
  //   height: StyleSheet.hairlineWidth,
  //   backgroundColor: colors['1104'],
  //   width: px2dp(657),
  // },
  moneyBox: {
    margin: px2dp(21),
  },
  moneyUpper: {
    flexDirection: 'row',
    // lineHeight: px2dp(45 + 7),
    textAlign: 'center',
  },
  figure: {
    fontSize: sizes.f6,
    color: colors['1001'],
  },
  littleTextStyle: {
    fontSize: sizes.f1,
    color: colors['1101'],
    textAlign: 'center',
  },
  addCardBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: px2dp(81),
    paddingHorizontal: px2dp(41 - 17),
  },
  middleTextStyle: {
    fontSize: sizes.f2,
    color: colors['1101'],
    // fontFamily: 'iconfont',
    // flexDirection: 'row',
    // height: px2dp(81),
    marginLeft: px2dp(20),
    // alignItems:'center',
    // textAlignVertical: 'center',
    // backgroundColor: 'blue',
  },
  addCardText: {
    marginLeft: px2dp(21),
  },
  iconfont: {
    // 小图标整体样式
    color: colors['1102'],
    fontFamily: 'iconfont',
    // alignItems: 'center',
    // width: px2dp(20),
    // height: px2dp(20),
  },
  iconfontCard: {
    // 银行卡小图标
    fontSize: px2dp(36),
    marginRight: px2dp(20),
  },
  iconfontMore: {
    // 更多小图标
    fontSize: px2dp(30),
  },
  blank: {
    marginTop: px2dp(20),
  },
  radioView: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    marginHorizontal: px2dp(20),
    height: px2dp(88),
  },
  cashValueBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    // paddingRight: px2dp(41 - 17),
  },
  cashValueRightText: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
    marginRight: px2dp(41 - 17),
  },
  cashValueDetailBox: {
    marginHorizontal: px2dp(40),
    marginVertical: px2dp(20),
    fontSize: sizes.f0,
    color: colors['1103'],
    lineHeight: px2dp(35),
  },
  clause: {
    paddingHorizontal: px2dp(20),
    lineHeight: px2dp(35),
    fontSize: sizes.f1,
    color: colors['1101'],
  },
  buttonStyle: {
    flexDirection: 'row',
    position: 'absolute',
    bottom: 0,
    width: '50%',
  },
  bankDetailText: {
    textAlign: 'left',
    lineHeight: px2dp(36),
    marginHorizontal: px2dp(41 - 17),
    marginVertical: 0,
  },
  firstPeriodCardDetailText: {
    marginVertical: px2dp(20),
  },
  firstPeriodCardBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  changeBankCardBox: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  changeBankCard: {
    fontSize: sizes.f1,
    color: '#F7914D',
    marginRight: px2dp(10),
  },
  changeBankCardMoreIconfont: {
    lineHeight: px2dp(133),
    marginRight: px2dp(41 - 17),
    marginLeft: px2dp(10),
  },
});
